package org.hoyi.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.hoyi.DB.ctrl.Console;

/**
 *
 * @author ljb 84024551@qq.com   2015年5月22日
 *
 */
public final class DomainUtil
{
	public static String getDomainWithSeparator(HttpServletRequest request)
	{
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
		return tempContextUrl;
	}

	public static String getDomainNotWithSeparator(HttpServletRequest request)
	{
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).toString();
		return tempContextUrl;
	}

	public static String getFullDomainUrl(HttpServletRequest request, String url)
	{
		if (StringUtils.isNotEmpty(url))
		{
			String newUrl = "";
			if (url.startsWith("/"))
				newUrl = getDomainNotWithSeparator(request) + url;
			else
				newUrl = getDomainWithSeparator(request) + url;
			return newUrl;
		}
		return url;
	}
	
	public static String GetRootURL(Class viewclass)
	{
		//WebRoot.usctrls.topNavCtrls
		//WebRoot.view.view/img/headpage/logo.png
		// 就是当前这个目录到根到底有几个。。/
		int thirdpoint = viewclass.toString().substring(6).split("\\.").length - 2;
		if (thirdpoint > 0) {
			String tmp = "";
			for (int i = 0; i < thirdpoint; i++) {
				tmp += "../";
			}
			return tmp;
		}
		
		return "";
		//return parent.getClass().toString();
	}
	
	/** 
	 * 减少一个层级的DomainUtil
	 * @param viewclass
	 * @return value
	 */
	public static String GetShowRootURL(Class viewclass)
	{
		//WebRoot.usctrls.topNavCtrls
		//WebRoot.view.view/img/headpage/logo.png
		// 就是当前这个目录到根到底有几个。。/
		int thirdpoint = viewclass.toString().substring(6).split("\\.").length - 2;
		if (thirdpoint > 0) {
			String tmp = "";
			for (int i = 2; i < thirdpoint; i++) {
				tmp += "../";
			}
			return tmp;
		}
		
		return "";
		//return parent.getClass().toString();
	}
	/**
	 * 有时候默认访问的路径，没有带上
	 * @param viewclass
	 * @param request
	 * @return value
	 */
//	public static String GetShowRootURL(Class viewclass, HttpServletRequest request){
//
//		int startsplitidx = 2;
//		
//		String requrl = request.getRequestURI();
//		if (requrl.endsWith(".hoyip")) {
//			int thirdpoint = viewclass.toString().substring(6).split("\\.").length - 2;
//			if (thirdpoint > 0) {
//				String tmp = "";
//				for (int i = 2; i < thirdpoint; i++) {
//					tmp += "../";
//				}
//				return tmp;
//			}
//			
//			return "";
//		}else{
//			return requrl + "/";
//		}
//	}
}
